package com.yds.developtools.utils

import android.app.Activity
import java.util.*
import kotlin.system.exitProcess

/**
 * 作者:     YDS
 * 创建时间: 2023/5/29 9:19
 * 页面描述: 应用程序Activity管理类：用于Activity管理和应用程序退出
 */
@Suppress("unused")
object YDSActivityStackHelper {
    private val activityStack = Stack<Activity>()

    /*** 作者: YDS 时间: 2023/5/29 9:36 描述: 获取栈内activity数量 ***/
    fun getCount(): Int = activityStack.size

    /*** 作者: YDS 时间: 2023/5/29 9:36 描述: 添加activity到栈内 ***/
    fun addActivity(activity: Activity) {
        if (activityStack.contains(activity)) {
            activityStack.remove(activity)
        }
        activityStack.add(activity)
    }

    /*** 作者: YDS 时间: 2023/5/29 9:35 描述: 获取栈顶activity ***/
    fun topActivity(): Activity? {
        return if (activityStack.isEmpty()) {
            null
        } else {
            activityStack.lastElement()
        }
    }

    /*** 作者: YDS 时间: 2023/5/29 9:35 描述: 查询指定activity ***/
    fun findActivity(cls: Class<*>): Activity? {
        for (activity in activityStack) {
            if (activity.javaClass == cls) {
                return activity
            }
        }
        return null
    }

    /*** 作者: YDS 时间: 2023/5/29 9:24 描述: 结束当前activity ***/
    fun finishActivity(cls: Class<*>) {
        for (activity in activityStack) {
            if (activity.javaClass == cls) {
                activity?.let {
                    activityStack.remove(it)
                    it.finish()
                }
                break
            }
        }
    }

    /*** 作者: YDS 时间: 2023/5/29 9:23 描述: 结束掉非当前activity的所有activity ***/
    fun finishOthersActivity(cls: Class<*>) {
        val iterator = activityStack.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity.javaClass != cls) {
                iterator.remove()
                activity.finish()
            }
        }
    }

    /*** 作者: YDS 时间: 2023/5/29 9:23 描述: app退出 ***/
    fun appExit() {
        try {
            finishAllActivity()
            android.os.Process.killProcess(android.os.Process.myPid())
            exitProcess(0)
        } catch (e: Exception) {
            exitProcess(-1)
        }
    }

    private fun finishAllActivity() {
        for (activity in activityStack) {
            activity.finish()
        }
        activityStack.clear()
    }
}